package handler

import (
	"encoding/json"
	"fmt"
	"net/http"
	"server/utils"

	"server/form"
	. "server/initialize"
	"server/model"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

func GetAllDataWebSocket(c *gin.Context) {
	var upGrader = websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}

	//升级get请求为webSocket协议
	ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}
	defer func() {
		ws.Close() //返回前关闭
		DapingNum--
		recover()
	}()

	//托管给wsList
	WsList = append(WsList, ws)
	DapingNum++
	for {
		//读取ws中的数据
		_, msg, err := ws.ReadMessage()
		if err != nil {
			continue
		}
		var ls []form.Position
		err = json.Unmarshal(msg, &ls)
		if err != nil {
			continue
		}
		Limit = ls
		fmt.Println("limit更新了!!")
	}
}

func MoveSocket(c *gin.Context) {
	var upGrader = websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}

	//升级get请求为webSocket协议
	ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}
	defer func() {
		ws.Close() //返回前关闭

		recover() // 截获到异常
	}()
	for {
		//读取ws中的数据
		_, message, err := ws.ReadMessage()
		if err != nil {
			ws.Close()
			continue
		}
		var req form.ReqMove
		err = json.Unmarshal(message, &req)
		if err != nil {
			continue
		}

		if req.Uuid != "" {
			data, err := model.GetDataByUUid(req.Uuid)
			if err != nil {
				if err.Error() == "不存在该key" {
					//写入ws数据
					err = ws.WriteMessage(1, []byte("不存在该uuid"))
					if err != nil {
						break
					}
				}
				continue
			}
			data.X = data.X + req.X
			data.Y = data.Y + req.Y

			if !Filter(data.X, data.Y) {
				// filer 为false 不会执行变更
				continue
			}

			model.ChangeDataByUUid(*data)
			MapChannel <- new(interface{})
		}
	}
}

// WebSocketTest websocket测试
// ws://127.0.0.1:8999/WebSocketTest
func WebSocketTest(c *gin.Context) {
	var upGrader = websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}

	//升级get请求为webSocket协议
	ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}
	defer func() {
		ws.Close() //返回前关闭
		recover()
		fmt.Println("链接断开了!!!")
	}()
	for {
		//读取ws中的数据
		mt, _, err := ws.ReadMessage()
		if err != nil {
			continue
		}

		//写入ws数据
		err = ws.WriteMessage(mt, []byte("收到你的信息了!!!!, 服务器尝试主动推送消息"))
		if err != nil {
			continue
		}

		marshal, err := json.Marshal(model.GetDataList())
		if err != nil {
			continue
		}
		//写入ws数据
		err = ws.WriteMessage(1, marshal)
	}

}

func Filter(X, Y int) (res bool) {
	res = utils.InPlane(0, 0, 0, 0, 0, 0)
	if res {
		// 如果在面内
		return false
	}

	res = utils.LessThanZero(X, Y)
	if res {
		//如果小于0
		return false
	}

	// true 代表可以通行
	return true
}
